{% extends 'base.html' %}
{% load patrowl_tags %}
{% block content %}

<ul class="breadcrumb">
  <li><a href="{% url 'list_engines_view' %}">engines</a></li>
  <li class="active">instances</li>
</ul>

<div class="container">
  <table class="table table-hover">
    <thead>
      <tr>
        <th>Type</th>
        <th>Name</th>
        <th>Funct. Status</th>
        <th>Oper.State</th>
        <th>API URL</th>
        <th>Last update</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
    {% for engine in engines %}
    <tr>
      <td>{{ engine.type }}</td>
      <td>{{ engine.name }}</td>
      {% if engine.enabled %}
      <td><span class="label label-success">Enabled</span></td>
      {% else %}
      <td><span class="label label-danger">Disabled</span></td>
      {% endif %}
      {% if engine.status == 'READY' %}
      <td><span class="glyphicon glyphicon-ok" style="color:green"></span> Ready</td>
      {% else %}
      <td><span class="glyphicon glyphicon-remove" style="color:red"></span> {{ engine.status }}</td>
      {% endif %}
      <td>{{ engine.api_url }}</td>
      <td>{{ engine.updated_at|smartdate }}</td>
      <td>
        <button type="button" class="btn btn-default btn-xs" aria-haspopup="true" aria-expanded="false" onclick="location.href='/engines/edit/{{ engine.id }}'">
          <span class="glyphicon glyphicon-edit"></span></button>
        <button type="button" class="btn btn-default btn-xs btn-engine-info" data-toggle="modal" data-target="#modal-info-engine" engine-id="{{ engine.id }}">
          <span class="glyphicon glyphicon-info-sign"></span></button>
        <button type="button" class="btn btn-default btn-xs btn-refresh-engine-status" aria-haspopup="true" aria-expanded="false" engine-id="{{ engine.id }}">
          <span class="glyphicon glyphicon-repeat"></span></button>
        <button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#modal-delete-engine"
           engine-id="{{ engine.id }}" engine-name="{{ engine.name }}@{{ engine.api_url}}">
          <span class="glyphicon glyphicon-remove"></span></button>
        {% if engine.enabled %}
        <button type="button" class="btn btn-warning dropdown-toggle btn-xs btn-change-status" aria-haspopup="true" aria-expanded="false" engine-id="{{ engine.id }}">
          Disable</button>
        {% else %}
        <button type="button" class="btn btn-success dropdown-toggle btn-xs btn-change-status" aria-haspopup="true" aria-expanded="false" engine-id="{{ engine.id }}">
          Enable</button>
        {% endif %}
      </td>
    </tr>
  {% endfor %}
  </tbody>
  </table>
  <a href="/engines/add">+ Add a new scan engine</a><br/>
  <a href="#" class="text-warning btn-refresh-all-engines">* Refresh scan engine status</a><br/>
  {% if autorefresh_status %}
    <a href="#" class="text-danger btn-autorefresh-all-engines">* Disable Auto-refresh scan engine status</a>
  {% else %}
    <a href="#" class="text-danger btn-autorefresh-all-engines">* Enable Auto-refresh scan engine status</a>
  {% endif %}

  {% if messages %}
  <ul class="messages">
      {% for message in messages %}
      <li>{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
      {% endfor %}
  </ul>
  {% endif %}
</div>


<!-- Delete Engine modal -->
<div class="modal fade" id="modal-delete-engine" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <!-- Modal Header -->
      <div class="modal-header bg-primary">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">&times;</span>
          <span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Delete engine</h4>
      </div>

      <!-- Modal Body -->
      <div class="modal-body">
        <div id="delete-engine">
          <!-- Content -->
        </div>
        Confirm Deleting?
        <button type="button" class="btn btn-xs btn-warning btn-delete-engine" data-dismiss="modal" autofocus>Yes</button>
        <button type="button" class="btn btn-xs btn-primary" data-dismiss="modal">No</button>
      </div>
    </div>
  </div>
</div>

<!-- Info Engine modal -->
<div class="modal fade" id="modal-info-engine" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <!-- Modal Header -->
      <div class="modal-header bg-primary">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">&times;</span>
          <span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Engine info</h4>
      </div>

      <!-- Modal Body -->
      <div class="modal-body">
        <div id="info-engine">
          <!-- Content -->
        </div>
        <button type="button" class="btn btn-xs btn-primary" data-dismiss="modal">Cancel</button>
      </div>
    </div>
  </div>
</div>


<script>
  // jQuery ready
  $(function() {

    // Info engine modal
    $("#modal-info-engine").on('show.bs.modal', function (e) {
      engine_id = e.relatedTarget.getAttribute('engine-id');
      xhr = $.ajax({
        url: "{% url 'info_engine_api' 0 %}".replace("0", engine_id),
        method: "GET",
        dataType: 'json',
        beforeSend: function(){
          $("div#info-engine").html("Loading...");
        },
        success: function(data, textStatus, jqXHR){
          info_data = "Engine: <b>"+data["engine"]["name"]+"</b><br/>";
          info_data+= "API URL: <b>"+data["engine"]["api_url"]+"</b><br/>";

          if(data["engine_infos"]["status"] == "ERROR") {
            info_data+= "Oper status: <b>ERROR</b><br/>";
            if(data["engine_infos"]["details"]){
              info_data+= "Request: <b>"+data["engine_infos"]["details"]["request"]+"</b></br>"
              info_data+= "Reason: <b>"+data["engine_infos"]["details"]["reason"]+"</b></br>"
            }
          } else {
            info_data+= "Nb scans: <b>"+data["nb_scans"]+"</b><br/>";
            info_data+= "Oper status: <b>"+data["engine_infos"]["engine_config"]["status"]+"</b><br/>";
            info_data+= "Version: <b>"+data["engine_infos"]["engine_config"]["version"]+"</b><br/>";
            info_data+= "Description: <b>"+data["engine_infos"]["engine_config"]["description"]+"</b><br/>";

            current_scans=data["current_scans"];
            if (current_scans == null || Object.keys(current_scans).length === 0) {
              info_data+= "Current scans: <b>no scan in progress</b><br/>";
            } else {
              info_data+= "Current scans: <br/>";
              for (var scan in current_scans){
                if (current_scans.hasOwnProperty(scan)) {
                  scan_id = Object.keys(current_scans[scan])[0];
                  info_data+= " * id="+scan_id+", started_at: "+new Date(current_scans[scan][scan_id]["started_at"])+", status: "+current_scans[scan][scan_id]["status"]+" <br/>";
                }
              }
            }
          }

          $("div#info-engine").html(info_data+"<br/><br/>");
        }
      });
    });

    // Delete engine modal
    $("#modal-delete-engine").on('show.bs.modal', function (e) {
      engine_id = e.relatedTarget.getAttribute('engine-id');
      engine_name = e.relatedTarget.getAttribute('engine-name');
      $("div#delete-engine").attr('engine-id', engine_id);
      $("div#delete-engine").html("Engine: <b>"+engine_name+"</b><br/><br/>");
    });
    $("button.btn-delete-engine").on('click', function (e) {
      engine_id = $("div#delete-engine").attr('engine-id');
      delete_engine_url = "{% url 'delete_engine_api' 0 %}".replace("0", engine_id);
      xhr = $.ajax({
        url: delete_engine_url,
        method: "DELETE",
        headers: {"X-CSRFToken": "{{ csrf_token }}"},
        success: function(){
          location.reload();
        }
      });
    });

    // Change engine status (enable-disable)
    $("button.btn-change-status").on('click', function(eventObject) {
      engine_id = eventObject.target.getAttribute('engine-id');
      engine_url = "{% url 'toggle_engine_status_api' 0 %}".replace("0", engine_id);
      xhr = $.ajax({
        url: engine_url,
        method: "PATCH",
        headers: {"X-CSRFToken": "{{ csrf_token }}"},
        success: function(){
          location.reload();
          if (data.status == "success") {
            console.log( "Status successfully updated!" );
            $("div.notifications").html('<div class="alert alert-dismissible alert-success fade in"><button type="button" class="close" data-dismiss="alert">&times;</button>Scan successfully enqueued</div>');
            $("div.notifications>div").delay(3000).fadeOut(
              function () {
                  $("div.notifications>div").remove();
              }
            );
          }
        }
      });
    });

    // Refresh an engine status
    $("button.btn-refresh-engine-status").on('click', function(eventObject) {
      engine_id = eventObject.currentTarget.getAttribute('engine-id');
      engine_url = "{% url 'get_engine_status_api' 0 %}".replace("0", engine_id);
      var xhr = $.get(engine_url, function(data) {
        location.reload();
        if (data.status == "success") {
          $("div.notifications").html('<div class="alert alert-dismissible alert-success fade in"><button type="button" class="close" data-dismiss="alert">&times;</button>Scan successfully enqueued</div>');
          $("div.notifications>div").delay(3000).fadeOut(
            function () {
                $("div.notifications>div").remove();
            }
          );
        }
      });
    });

    // Refresh all engine status
    $("a.btn-refresh-all-engines").on('click', function() {
      engine_url = "{% url 'refresh_engines_status_api' %}";
      var xhr = $.get(engine_url, function(data) {
        if (xhr.status == 200) {
          $("div.notifications").html('<div class="alert alert-dismissible alert-success fade in"><button type="button" class="close" data-dismiss="alert">&times;</button>Action enqueued</div>');
          $("div.notifications>div").delay(3000).fadeOut(
            function () {
              $("div.notifications>div").remove();
            }
          );
        }
        location.reload();
      })
    });

    // Auto-Refresh all engine status
    $("a.btn-autorefresh-all-engines").on('click', function() {
      autorefresh_url = "{% url 'toggle_autorefresh_engine_status_api' %}";
      var xhr = $.get(autorefresh_url, function(data) {
        if (xhr.status == 200) {
          if (data.autorefresh_task_status == true){
            $("a.btn-autorefresh-all-engines").html("* Disable Auto-refresh scan engine status");
          } else {
            $("a.btn-autorefresh-all-engines").html("* Enable Auto-refresh scan engine status");
          }
        }
        //location.reload();
      });
    });

  });
</script>
{% endblock %}
